package com.loop.unclelend.utils

import android.content.Intent
import android.net.Uri
import android.provider.ContactsContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import com.loop.unclelend.pro.ProActivity

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/8/20 15:23
 * @Annotation：选择联系人
 */
class UnclePickContactUtils(private val proAct: ProActivity) {

    // 临时回调接收器
    private var pickContactCallback: ((contactName: String, contactMobile: String) -> Unit)? = null

    // 通讯录启动器
    private val contactLauncherBus = proAct.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        if (it == null || it.resultCode != AppCompatActivity.RESULT_OK)
            return@registerForActivityResult
        it.data?.data?.let { uri ->
            pickContactAction(uri) // 从返回的Uri解析出联系人
        }
    }

    /** 从通讯录选取联系人 */
    fun startPickContact(callback: (contactName: String, contactMobile: String) -> Unit) {
        pickContactCallback = callback
        contactLauncherBus.launch(
            Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
        )
    }

    /**
     * 解析联系人数据
     */
    private fun pickContactAction(contactUri: Uri){
        var displayName = ""
        var phoneNumber = ""
        val projection = arrayOf(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER)
        proAct.contentResolver.query(contactUri, projection, null, null, null)?.use {
            if (it.moveToFirst()) {
                val nameIndex = it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
                displayName = it.getString(nameIndex)
                val phoneIndex = it.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                phoneNumber = it.getString(phoneIndex)
            }
        }
        pickContactCallback?.invoke(displayName, phoneNumber)
    }
}